<template>
  <div class="notice-board">
    <!-- 公告列表 -->
    <div class="notice-list">
      <el-card
        v-for="(notice, index) in notices"
        :key="index"
        @click.native="viewNotice(notice)"
      >
        <p class="notice-title">{{ notice.title }}</p>
        <p class="notice-date">{{ notice.date }}</p>
        <!-- 显示发布人/部门的姓名 -->
        <p class="notice-author">{{ notice.author }}</p>
      </el-card>
    </div>

    <!-- 公告详情 -->
    <div class="notice-detail" v-if="selectedNotice">
      <h2 style="text-align:center">{{ selectedNotice.title }}</h2>
      <p>{{ selectedNotice.date }} &nbsp; {{ selectedNotice.author }}</p>
      <div class="notice-content">{{ selectedNotice.content }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      notices: [], // 存储公告列表
      selectedNotice: null, // 选中的公告
    };
  },
  created() {
    this.fetchNotices();
  },
  methods: {
    viewNotice(notice) {
      this.selectedNotice = notice;
    },
    formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    // return `${year}-${month}-${day} ${hours}:${minutes}`;
    return `${year}-${month}-${day}`;
  },
    fetchNotices() {
      this.$http.get('/notifications/all')
        .then(response => {
          // 后端返回的数据直接是公告数组
          this.notices = response.data.map(notice => ({
            title: notice.notiTitle,
            date: this.formatDate(new Date(notice.notiTimestamp)), // 注意这里可能需要格式化日期
            content: notice.notiContent,
            author: notice.notiSender,
          }));
        })
        .catch(error => {
          console.error("Error fetching notices:", error);
        });
    },
    viewNotice(notice) {
      this.selectedNotice = notice;
    },
  },
};
</script>

<style scoped>
.notice-board {
  display: flex;
}

.notice-list {
  flex: 1;
}

.notice-list .el-card {
  margin-bottom: 10px;
  cursor: pointer;
}

.notice-title {
  font-size: 16px;
  font-weight: bold;
}

.notice-date {
  color: #888;
}

.notice-author {
  color: #888;
  text-align: right; /* 公告尾部向右对齐 */
}

.notice-detail {
  flex: 2;
  padding: 20px;
}

.notice-detail h2 {
  font-size: 24px;
  font-weight: bold;
}

.notice-detail p {
  color: #888;
}

.notice-content {
  margin-top: 20px;
}
</style>
